//引入express模块
var express = require('express');
//创建APP
var app = express();
//创建Server
var server=require('http').createServer(app);
//引入body-parser用来接收post请求的数据
var bodyParser=require('body-parser');
//引入MD5加密模块
var md5=require('./md5');
//引入用户数据源
var users=require('./datasource/user');
//引入PATH
var path=require('path');
//解析POST数据
app.use(bodyParser.urlencoded({extended:true}))

//托管静态文件
app.use(express.static(__dirname+'/src'));

//网站的入口
app.get('/',(req,res) => {
  res.sendFile(__dirname+'/src/pages/index.html');
})

//登录
app.post('/login.do',(req,res) =>{
  let username = req.body.username;
  let password = md5(req.body.password);

  if(!username || !password){
    res.send('fail');
    return;
  }

  for(u of users){
    if(u.username === username && u.password=== password && u.state==1){
      res.send('success');
      return;
    }
  }
  res.send('fail');
})

//查询用户列表
app.get('/users.do',(req,res) =>{
  res.send(users);
})


//重置用户密码
app.post('/resetPass.do', (req, res) => {
  let id = req.body.id;
  let new_pass = req.body.password;
  for (u of users) {
    if (u.id == id) {
      u.password = md5(new_pass);
      res.send('success');
      return;
    }
  }
  res.send('fail');
})


// 修改用户状态(1:正常；0：冻结)
app.post('/change_state.do', (req, res) => {
  let id = req.body.id;
  let state = req.body.state;
  for (u of users) {
    if (u.id == id) {
      u.state = state;
      res.send('success');
      return
    }
  }
  res.send('fail')
})


// 添加用户
app.post('/addUser.do',(res,req)=>{
  let username=req.body.username;
  let password=md5(req.body.password);
  let phone=req.body.phone;
  let id=users[users.length-1].id+1;
  let state=1;
  Users.push({
    username,password,state,id
  })
  res.send('success')
})

server.listen(8000);
console.log('=====Hotel Manage Startup Success in 8000=====');